package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect() throws UnsupportedEncodingException {
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""
        return R.ok().data(map);
    }

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {

        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        try {
            String jsonStr = HttpClientUtils.get(accessTokenUrl);

            //获取json数据的两种方法
            //方法一
            //Gson gson = new Gson();
            //Map map = gson.fromJson(jsonStr, Map.class);
            //String openid=(String) map.get("openid");
            //String access_token=(String) map.get("access_token");
            // 方法二
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            UserInfo userInfo = userInfoService.selectByOpenId(openid);

            if (userInfo==null){
                //第三步 拿着openid  和  access_token请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo:"+resultInfo);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
//                String headimgurl = resultUserInfoJson.getString("headimgurl");

                userInfo = new UserInfo();
                userInfo.setStatus(1);
                userInfo.setCreateTime(new Date());
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
//                userInfo.setCertificatesUrl(headimgurl);

                userInfoService.save(userInfo);
            }

            //已经存在用户：刚注册新用户，老用户
            Map<String, Object> map = new HashMap<>();

            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);

            //和手机登录不同的，多返回一个openid
            //判断根据openid查询出来的userinfo中手机号是否为空，为空，
            //说明微信号和手机号还没有绑定过，返回openid
            //前端拿到不为空的openid，说明需要做手机号的绑定
            if(StringUtils.isEmpty(userInfo.getPhone())){
                map.put("openid",openid);//如果openid不为空，微信号和手机号没有绑定过，前端需要绑定
            }else {
                map.put("openid","");//如果openid为空，微信号和手机号绑定过了
            }

            //跳转到前端页面
            return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode((String) map.get("name"),"utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}